//
//  HMNetworkTools.swift
//  AFN
//
//  Created by 王寒 on 16/4/8.
//  Copyright © 2016年 wanghan. All rights reserved.
//

import UIKit
import AFNetworking
//使用结构体来定义接口名称
struct API{
    static let onlineHost = "https://api.weibo.com/"
    static let authrizon = "oauth2/access_token"
    static let access_token = "2/users/show.json"
    static let homepage = "2/statuses/home_timeline.json"
}


enum HMMethods: String{
    case POST = "POST"
    case GET = "GET"
    
}

//声明单例对象
class HMNetworkTools: AFHTTPSessionManager {

    static let tool: HMNetworkTools = {
        let manager = HMNetworkTools(baseURL: NSURL(string: API.onlineHost))
        
        manager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return manager
        
    }()
    
}

//MARK:首页数据获取
extension HMNetworkTools{
    
    func loadHomePage(token: String,finished:(result: AnyObject?,error: NSError?) -> ()){
        let parameter = ["access_token" : token]
        print(token)
        request(.GET, urlString: API.homepage, parameters: parameter) { (responObject, error) -> () in
            finished(result: responObject, error: error)
        }
    }
}

//MARK:登录和注册
extension HMNetworkTools{
    //MARK:根据code获取token
    func loadAccessToken(code: String,finished: (result: AnyObject?,error: NSError?) -> ()){

        let parametes = ["client_id":client_id,
            "client_secret" : client_secret,
            "grant_type"    :  "authorization_code",
            "code"          : code,
            "redirect_uri"  : redirect_uri]
        
        request(.POST, urlString: API.authrizon, parameters: parametes, success: finished)
        
    }
    
    //MARK:获取用户信息
    func loadUserInfo(token: AnyObject,uid: AnyObject,success:(responObject: AnyObject?,error: NSError?) -> ()){
  
        let parame = ["access_token": token,"uid": uid]
    
        request(.GET, urlString: API.access_token, parameters: parame, success: success)
    }
    
    
}




//MARK:网络请求核心方法 GET POST
extension HMNetworkTools{
    
    func request(httpMethod: HMMethods,urlString: String,parameters: AnyObject?,success:(responObject: AnyObject?,error: NSError?) -> ()){
        
        let successOK = {(dask: NSURLSessionDataTask, respondObject: AnyObject?) -> Void in
            
            success(responObject: respondObject, error: nil)
            
        }
        
        
        let failure = { (task: NSURLSessionDataTask?, error: NSError) -> Void in
            //执行失败的回调
            success(responObject: nil, error: error)
        }
        
        
        if httpMethod == HMMethods.GET{
            GET(urlString, parameters: parameters, progress: nil, success: successOK, failure: failure)
        }else{
            POST(urlString, parameters: parameters, progress: nil, success: successOK, failure: failure)
        }
        
        
    }

}